<?php
$db = new Database();
$fs = new functions();
$auth = Auth::getAuth('current_user');
$email = new Mail_Notification();
$userCompany = new userQueries();
    // Registration Values
        $action = $_POST['action'];
        $regEmail =  stripslashes(htmlspecialchars($_POST['regEmail'],ENT_QUOTES));
        $regDisplayName =  stripslashes(htmlspecialchars($_POST['regDisplayName'],ENT_QUOTES));
        $regFname =  stripslashes(htmlspecialchars($_POST['regFname'],ENT_QUOTES));
        $regLname =  stripslashes(htmlspecialchars($_POST['regLname'],ENT_QUOTES));
        $regPosition  =  stripslashes(htmlspecialchars($_POST['regPosition'],ENT_QUOTES));
        
    if(isset($action)){
        
        // User Registration - save/add to the database
        if($action=="registerUser"){
            if($db->query("SELECT * FROM tbuser WHERE email={$db->escape($regEmail)}","numrows")>0){
                echo "Your email is already registered.";
            }else{
                if(!$fs->VerifyMailAddress($regEmail)){
                    echo "Please type your correct email format.";
                }else{
                    $date = $fs->currentDateTime();
                    $password = $fs->encrypt_decrypt("encrypt", "password");
                    // Save user to db
                        $insertUser = array("email"=>$regEmail,"display_name"=>$regDisplayName,
                                            "first_name"=>$regFname,"last_name"=>$regLname,
                                            "position"=>$regPosition,
                                            "password"=>$password,"company_id"=>$auth['company_id'],
                                            "user_level_id"=>"3",
                                            "date_registered"=>$date,"is_active"=>1);
                            $userID = $db->insert("tbuser",$insertUser);
                    // Audit Logs
			$userCompany->auditLogs($auth,"tbuser","8",$userID);
                            
                                        
                    // Send Email Confirmation
                        echo $email->notify_user("regUser","Company_Only",$userID,"user");
                        
                        
                            echo "User was successfully saved.";
                }
            }
        }
        
        // Update User
        // User Registration - save/add to the database
        if($action=="updateUser"){
            $userID = stripslashes(htmlspecialchars($_POST['userID'],ENT_QUOTES));
            $regEmail = stripslashes(htmlspecialchars($_POST['editEmail'],ENT_QUOTES));
            $regDisplayName = stripslashes(htmlspecialchars($_POST['editDisplayName'],ENT_QUOTES));
            $regFname = stripslashes(htmlspecialchars($_POST['editFname'],ENT_QUOTES));
            $regLname = stripslashes(htmlspecialchars($_POST['editLname'],ENT_QUOTES));
            $regPosition  = stripslashes(htmlspecialchars($_POST['editPosition'],ENT_QUOTES));
            $regActive = stripslashes(htmlspecialchars($_POST['editActive'],ENT_QUOTES));
            $regPrivileges = stripslashes(htmlspecialchars($_POST['editPrivileges'],ENT_QUOTES));
            $type = stripslashes(htmlspecialchars($_POST['type'],ENT_QUOTES));
            if($db->query("SELECT * FROM tbuser WHERE email={$db->escape($regEmail)} AND id!={$db->escape($userID)}","numrows")>0){
                echo "Your email is already registered.";
            }else{
                if(!$fs->VerifyMailAddress($regEmail)){
                    echo "Please type your correct email format.";
                }else{
                    
                    $date = $fs->currentDateTime();
                    // Save user to db
                    
                        // Update Company
                            //$updateCompany = array("email"=>$regEmail);
                            //$con = array("id"=>$auth['company_id']);
                            //     $db->update("tbcompany",$updateCompany,$con);
                        //Update User

                            $updateUser = array("email"                         =>      $regEmail,
                                                "display_name"                  =>      $regDisplayName,
                                                "first_name"                    =>      $regFname,
                                                "last_name"                     =>      $regLname,
                                                "position"                      =>      $regPosition,
                                                "is_active"                     =>      $regActive,
                                                "user_level_id"                 =>      $regPrivileges
                                                );
                            $con = array("id"=>$userID);
                                $db->update("tbuser",$updateUser,$con);
                            // Audit Logs
                                $userCompany->auditLogs($auth,"tbuser","21",$userID);
                                
				// $login = $db->query("SELECT *
				// 		    FROM tbuser
				// 		    WHERE id={$db->escape($userID)} ","row");
				// 		    Auth::setAuth('current_user',$login);
                    //  Send Email Confirmation
                            echo "User was successfully updated.";
                }
            }
        }
        
        
        // Delete / Deactivate User 
        elseif($action=="deleteUser"){
            $userID = $_POST['userID'];
            $loggedAccount = $_POST['loggedAccount'];
            
            if($userID==$auth['id']&&$loggedAccount=="del"){
                echo "Deactivate User logged.";
            }else{
                if($loggedAccount=="logout"){
                    $condition = array("id"=>$userID);
                    $set = array("is_active"=>0);
                    
                    $db->update("tbuser",$set,$condition);
                    
                    echo "User will now deactivate.";
                }else{
                    $condition = array("id"=>$userID);
                    $set = array("is_active"=>0);
                    
                    $db->update("tbuser",$set,$condition);
                    echo "User will now deactivate.";
                }
            }
            // Audit Logs
                $userCompany->auditLogs($auth,"tbuser","22",$userID);
        }
        
        
        // Get User
        elseif($action=="getUser"){
            $search = "";
            if(isset($_POST['search'])){
                $search = $_POST['search'];
            }

            
            $getCompanyUser = $db->query("SELECT * FROM tbuser WHERE company_id={$db->escape($auth['company_id'])} AND is_active={$db->escape(1)} AND (first_name LIKE '%". $search ."%' OR last_name LIKE '%". $search ."%') ORDER BY first_name ASC","array");
            foreach($getCompanyUser as $user){
                $u[] = array("userID"       =>  $user['id'],
                             "name"         =>  $user['first_name'] . " " . $user['last_name'],
                             "avatar"       =>  $userCompany->avatarPic("tbuser",$user['id'],"20","20","small","avatar")
                            );
            }
            echo json_encode($u);
        }
        
        // Get User Information
        elseif($action=="getUserInfo"){
            $userID = $_POST['userID'];
            $getUserInfo = $db->query("SELECT * FROM tbuser WHERE id={$db->escape($userID)}","row");
            
                $user[] = array("userID"                        =>      $getUserInfo['id'],
                                "email"                         =>      $getUserInfo['email'],
                                "displayName"                   =>      $getUserInfo['display_name'],
                                "firstName"                     =>      $getUserInfo['first_name'],
                                "lastName"                      =>      $getUserInfo['last_name'],
                                "contactNumber"                 =>      $getUserInfo['contact_number'],
                                "position"                      =>      $getUserInfo['position'],
                                "companyID"                     =>      $getUserInfo['company_id'],
                                "userLeveID"                    =>      $getUserInfo['user_level_id'],
                                "departmentPositionLevel"       =>      $getUserInfo['department_position_level'],
                                "password"                      =>      $getUserInfo['password'],
                                "extension"                     =>      $getUserInfo['extension'],
                                "dateRegister"                  =>      $getUserInfo['date_registered'],
                                "emailActivate"                 =>      $getUserInfo['email_activate'],
                                "isAvailable"                   =>      $getUserInfo['is_available'],
                                "isActive"                      =>      $getUserInfo['is_active'],
                                "departmentID"                  =>      $getUserInfo['department_id'],
                                "images"                        =>      $userCompany->avatarPic("tbuser",$getUserInfo['id'],"44","44","small","avatar")
                                );
                echo json_encode($user);
        }else if($_POST['action']=="forgot_password"){
            $uEmail = $_POST['email'];
            if($uEmail!=""){
                $getEmail = "SELECT * FROM tbuser WHERE email = {$db->escape($uEmail)} AND is_active=1";
                $getUser = $db->query($getEmail,"row");
                $countUser = $db->query($getEmail,"numrows");
                if($countUser==1){
                    $update = array("forgot_password"=>1);
                    $where = array("email"=>$uEmail);
                    $update = $db->update("tbuser",$update,$where);

                    //for email
                    $id = functions::base_encode_decode("encrypt", $getUser['id']);
                        // Sending Mail
                        $email->recover_password(array($getUser['email']=>$getUser['display_name']),"",$getUser['company_id'],"password",$id);
                        
                    $message = array("status"=>"success","message"=>"Your password was successfully reset. Please visit your email and get your password.!");
                    //
                }else{
                    //error
                    $message = array("status"=>"error","message"=>"Email is not valid");
                }
            }else{
                $message = array("status"=>"error","message"=>"Please type your email address");
            }
            // Audit Logs
                $userCompany->auditLogs($auth,"tbuser","23",$getUser['id']);
            echo json_encode($message);
        }
    }
?>